import {
  Controller,
  Req,
  Res,
  Get,
  Post,
  UseGuards,
  HttpCode,
} from '@nestjs/common';
import { LoginService } from './login.service';
import * as svgCaptcha from 'svg-captcha';
import { AuthService } from 'src/services/auth.service';
import { LocalAuthGuard } from 'src/guards/local-auth.guard';
import { SkipAuth } from 'src/decorators/skipAuth';
import { CheckCpatchaGuard } from 'src/guards/check-captcha.guard';

@SkipAuth()
@Controller()
export class LoginController {
  constructor(
    private readonly loginService: LoginService,
    private readonly authService: AuthService,
  ) {}

  @Get('captcha')
  getCaptcha(@Req() req, @Res() res) {
    const captcha = svgCaptcha.create({
      size: 4, //生成几个验证码
      fontSize: 50, //文字大小
      width: 100, //宽度
      height: 34, //高度
      background: '#cc9966', //背景颜色
    });
    req.session.captcha = captcha.text; //存储验证码记录到 session
    res.type('image/svg+xml');
    res.send(captcha.data);
  }

  @UseGuards(CheckCpatchaGuard, LocalAuthGuard) // 校验验证码、身份信息
  @HttpCode(200)
  @Post('login')
  async login(@Req() req, @Res() res) {
    res.send({
      code: 0,
      data: await this.authService.getToken(req.user),
      msg: '登录成功',
    });
  }
}
